package com.example.dsplatform.Controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.GatewayConfig;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.example.dsplatform.Dao.Mapper.OrderMapper;
import com.example.dsplatform.Service.OrderService;

import com.example.dsplatform.config.AlipayConfig;
import com.example.dsplatform.pojo.Entity.AlipayBean;
import com.example.dsplatform.pojo.Entity.Order;
import com.example.dsplatform.pojo.Entity.ResponseResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

import static com.example.dsplatform.utls.timeStamp.time;

@RestController
@ApiOperation(value = "支付接口")
@RequestMapping("/Alipay")
public class AlipayController {
    @Autowired
    AlipayConfig alipayConfig;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderMapper orderMapper;
    @PostMapping("/pay")

    /**
     * @param AlipayBean alipayBean
     * {
     *
     * }
     * @discription 实现按照名称查询功能
     * @return
     */
    public ResponseResult pay(@RequestBody AlipayBean alipayBean) throws Exception{
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGateWayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType());
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
       /* log.info("封装请求支付宝付款参数为:{}", JSON.toJSONString(alipayRequest));*/
       /* log.info("请求支付宝付款返回参数为:{}", result);*/
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return new ResponseResult(200,"测试成功",result);

    }
    /**
     * @param order
     * {
     *     "username":""
     * }
     * @discription 实现按照名称查询功能
     * @return
     */
    @RequestMapping("/pay2")
    public ResponseResult pay2(@RequestBody Order order) throws Exception {
        //接口模拟数据
        order.setOrderNo("001");
        order.setStatus("待支付");

        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGateWayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType());
        //扫码支付使用AlipayTradePrecreateRequest传参，下面调用的是execute方法
        AlipayTradePrecreateRequest precreateRequest = new AlipayTradePrecreateRequest();
        precreateRequest.setReturnUrl(alipayConfig.getReturnUrl());
        precreateRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
        precreateRequest.setBizContent(JSON.toJSONString(order));
        /*log.info("封装请求支付宝付款参数为:{}", JSON.toJSONString(precreateRequest));*/

        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(precreateRequest);
        } catch (AlipayApiException e) {
            throw new Exception(String.format("下单失败 错误代码:[%s], 错误信息:[%s]", e.getErrCode(), e.getErrMsg()));
        }
    /*    log.info("AlipayTradePrecreateResponse = {}", response.getBody());*/

        /*
        {
        "code": "10000",
        "msg": "Success",
        "out_trade_no": "815259610498863104",
        "qr_code": "https://qr.alipay.com/bax09455sq1umiufbxf4503e"
        }
        */
        if (!response.isSuccess()) {
            throw new Exception(String.format("下单失败 错误代码:[%s], 错误信息:[%s]", response.getCode(), response.getMsg()));
        }
        // TODO 下单记录保存入库
        // 返回结果，主要是返回 qr_code，前端根据 qr_code 进行重定向或者生成二维码引导用户支付
        JSONObject jsonObject = new JSONObject();
        //支付宝响应的订单号
        String outTradeNo = response.getOutTradeNo();
        jsonObject.put("outTradeNo",outTradeNo);
        //二维码地址，页面使用二维码工具显示出来就可以了
        jsonObject.put("qrCode",response.getQrCode());
        return new ResponseResult(200,"成功");
    }


    /**
     * 手机扫码支付
     * @param alipayBean
     * @return
     * @throws Exception
     */


}
